<!-- 商品列表 -->
<template>
  <h2 style="color: #595959; margin-bottom: 20px">
    {{ $t("messages.ProductList") }}
  </h2>

  <div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="expand">
        <template #default="scope">
          <el-form label-position="left" style="margin-left: 50px">
            <el-form-item label="商品ID：">
              <span>{{ scope.row.id }}</span>
            </el-form-item>
            <el-form-item label="所属分类：">
              <span>{{ scope.row.category }}</span>
            </el-form-item>
            <el-form-item label="创建时间：">
              <span>{{ scope.row.ctime }}</span>
            </el-form-item>
            <el-form-item label="商品销量：">
              <span>{{ scope.row.sellCount }}</span>
            </el-form-item>
            <el-form-item label="商品图片：">
              <img
                :src="scope.row.imgUrl"
                alt="商品图片"
                style="width: 100px; height: auto"
              />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="category" label="所属分类"></el-table-column>
      <el-table-column prop="price" label="商品价格"></el-table-column>
      <el-table-column label="商品图片">
        <template #default="scope">
          <img
            :src="scope.row.imgUrl"
            alt="商品图片"
            style="width: 100px; height: auto"
          />
        </template>
      </el-table-column>
      <el-table-column prop="goodsDesc" label="商品描述"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            style="
              background-color: #409eff;
              color: #fff;
              width: 60px;
              height: 30px;
            "
            type="text"
            size="small"
            @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            style="
              border: 1px solid #e8e8e8;
              background-color: #e55443;
              color: #fff;
              width: 60px;
              height: 30px;
            "
            type="text"
            size="small"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- .分页器 -->
    <el-pagination
      style="margin-top: 10px"
      background
      layout="total, sizes ,prev, pager, next"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    >
      >
    </el-pagination>
    <!-- .对话框 -->
    <el-dialog
      center
      lock-scroll
      draggable
      title="商品信息"
      v-model="dialogVisible"
      width="50%"
      @close="dialogVisible = false"
    >
      <el-form :model="dialogform">
        <el-form-item label="商品名称" style="margin-left: 20px">
          <el-input v-model="dialogform.name" style="width: 95%"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" style="margin-left: 20px">
          <el-input v-model="dialogform.category" style="width: 95%"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" style="margin-left: 20px">
          <el-input style="width: 95%" v-model="dialogform.price"> </el-input>
        </el-form-item>
        <el-form-item label="商品描述" style="margin-left: 20px">
          <el-input
            type="textarea"
            style="width: 95%"
            v-model="dialogform.goodsDesc"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片" style="margin-left: 20px">
          <el-upload
            style="border: 1px dash #e8e8e8"
            class="avatar-uploader"
            action="http://127.0.0.1:5000/goods/goods_img_upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="dialogform.imgUrl"
              :src="dialogform.imgUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { format } from "date-fns";
// 接口
import { getGoodsList, deleteGoods, editGoods } from "@/api/index.js";

const tableData = ref([]); // 表格数据
const headerImg = "http://127.0.0.1:5000/upload/imgs/goods_img/"; // 头像
const total = ref(50); // 总数据量
const pageSize = ref(4); // 每页显示的数据量(search)
const currentPage = ref(1); // 当前页码(search)
const dialogVisible = ref(false);
const dialogform = reactive({
  name: "",
  category: "",
  price: "",
  goodsDesc: "",
  imgUrl: "",
});

// 日期格式处理函数  ISO 8601 标准的日期时间
const formatDate = (dateString) => {
  return format(new Date(dateString), "yyyy-MM-dd HH:mm:ss");
};

const handleExpandChange = (row, expandedRows) => {
  console.log(row);

  row.ctime = formatDate(row.ctime);
};

// .分页器
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getGoodsListFn();
};

// 每页条目数改变时的处理函数
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置为第一页
  getGoodsListFn();
};

const handleAvatarSuccess = (response, file) => {
  // 处理上传成功
  dialogform.imgUrl = URL.createObjectURL(file.raw);
};

// 获取商品列表
const getGoodsListFn = async () => {
  const res = await getGoodsList({
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  });
  console.log("商品列表:", res);
  res.data.forEach((item) => {
    // 判断是否是新添加的图片
    if (item.imgUrl.indexOf("blob") === -1) {
      item.imgUrl = headerImg.concat(item.imgUrl);
    }
  });
  tableData.value = res.data;
};

// 编辑操作
const handleEdit = (row) => {
  console.log("row", row);
  dialogVisible.value = true;
  Object.assign(dialogform, row);
};

const submitForm = async () => {
  dialogVisible.value = false;
  console.log("dialogform", dialogform);

  const res = await editGoods(dialogform);
  if (res.code === 0) {
    getGoodsListFn();
    ElMessage({
      type: "success",
      message: "编辑成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "编辑失败",
    });
  }
};

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除本件商品吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await deleteGoods({
        id: row.id,
      });
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        getGoodsListFn();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

onMounted(() => {
  getGoodsListFn();
});
</script>

<style scoped>
::v-deep .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px dashed #515151;
}
</style>
